import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:robot3/pojo.dart';
import 'package:robot3/services.dart';
import 'dart:ui';

import 'package:robot3/widgets.dart';

import 'Robot.dart';
import 'backButton1.dart'; // For devicePixelRatio

// import 'widgets.dart';

// Extension for double
extension PxConversion on double {
  // Converts the value (assumed to be in px) to logical pixels
  double get toLogicalPixels {
    print("window.devicePixelRatio:" + window.devicePixelRatio.toString());
    return this / window.devicePixelRatio;
  }
}


//  商品库详情
void main() {
  runApp(const FanganKu());
}

class FanganKu extends StatelessWidget {
  const FanganKu({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: FangankuScreen(title: 'Flutter Demo Home Page'),

    );
  }
}

class FangankuScreen extends StatefulWidget {

  const FangankuScreen({super.key, required this.title});

  final String title;

  @override
  State<FangankuScreen> createState() => _PageState();
}

class _PageState extends State<FangankuScreen> {
  static const platform = MethodChannel('com.abc.robot01.xiangqing');
  String dataShared = 'No data';
  // String  accessToken="ed8a4b93-873d-42eb-85e7-19bf74cbb053";
  String  id="1bdc4e2b35764b46b133481f0807e5d6";
  String?  name="";
   Commodity? commodity;  // 声明 Commodity 类型的变量
  @override
  void initState() {
    super.initState();
    login().then((result) {
      if (result == 1) {
        print("登录成功");
        getProductById(id).then((commodity){
          setState(() {
            this.commodity = commodity;
            // name = commodity.name;
          });
        });
      } else {
        print("登录失败");
      }
    }).catchError((error) {
      // 处理错误
      print("发生错误: $error");
    });
    // getId();
    //
  }

  Future<void> getId() async {
    var sharedData = await platform.invokeMethod('getId');
    if (sharedData != null) {
      print(sharedData);
      setState(() {
        dataShared = sharedData;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // Image equivalent to the Image composable
          Image.asset(
            'images/bg.png', // 替换为你的图片路径
            fit: BoxFit.cover,
            width: double.infinity,
            height: double.infinity,
          ),
          Padding(
            padding: const EdgeInsets.all(
               30.0/ratio, // 像素值直接使用 dp 转换
            ),
            child:  commodity ==null ? Center(child: CircularProgressIndicator()):  // 加载完成后显示商品信息
            Stack(
              // crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                BackButton1(),
                Align(
                  alignment: Alignment.center,
                  child: Column(
                    children: [
                      TitleText(text: dataShared),
                      RobotCard(
                        child:
                        Padding(
                          padding: const EdgeInsets.all(30.0/ratio, // 像素值直接使用 dp 转换
                          ),
                          child: Column(
                            // mainAxisAlignment:MainAxisAlignment.end ,
                          // crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                          Container(
                          decoration: BoxDecoration(
                          color: Colors.transparent, // 设置背景颜色
                            borderRadius: BorderRadius.circular(10), // 可选：设置圆角
                          ),
                          child:
                          Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                RobotListWidget(ratio: ratio,),
                                SizedBox(width: 20 / ratio),
                                //大图：
                                Container(
                                  width: 500 / ratio, // 固定宽度
                                  height: 540 / ratio,
                                  color: Colors.red,
                                ),
                                SizedBox(width: 10/ratio,),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  spacing: 30/ratio,
                                  children: [
                                  Container(
                                    color: Colors.blue, // 背景颜色便于观察效果
                                    width: 604 / ratio, // 固定宽度
                                    // child:    TitleText30(text: '轻奢风全通体奶油白色格栅栅瓷砖卫生浴室厕墙砖地砖'),
                                    child:    TitleText30(text: '${commodity!.name}'),
                                  )
                               ,
                                  Text("¥21",
                                      maxLines: 300,
                                      overflow: TextOverflow.ellipsis,
                                      style: const TextStyle(
                                        fontSize: 42/ratio,
                                        color: Colors.red,
                                        fontWeight: FontWeight.normal,
                                        letterSpacing: 0.0,
                                        wordSpacing: 0.0, // 设置单词间距
                                      )),

                                    Row(children: [
                                      Text("风        格",
                                          maxLines: 300,
                                          overflow: TextOverflow.ellipsis,
                                          style: const TextStyle(
                                            fontSize: 24/ratio,
                                            color: MyBlack,
                                            fontWeight: FontWeight.normal,
                                            letterSpacing: 0.0,
                                            wordSpacing: 0.0, // 设置单词间距
                                          )),
                                       SizedBox(width: 20,),

                                      Text("奶油风",
                                          maxLines: 300,
                                          overflow: TextOverflow.ellipsis,
                                          style: const TextStyle(
                                            fontSize: 24/ratio,
                                            color: MyBlack,
                                            fontWeight: FontWeight.normal,
                                            letterSpacing: 0.0,
                                            wordSpacing: 0.0, // 设置单词间距
                                          )).withBackgroundAndPadding(),





 ],)




                                ],)




                              ],
                            )),

                            TitleText(text: '参数'),
                            TitleText(text: '内容20191'),
                            TitleText(text: '内容20191'),
                            // TitleText(text: '内容20191'),
                            // TitleText(text: '内容20191'),
                            // TitleText(text: '内容20191'),
                            // TitleText(text: '内容20191'),
                            // TitleText(text: '内容20191'),
                            // TitleText(text: '内容20191'),
                            // TitleText(text: '内容20191'),
                            // TitleText(text: '内容20191'),
                          ],
                        ),
                      ),),
                    ],
                  ),
                ),
              ],
            ),
          ),
          // Row(
          //   children: [
          //     SizedBox(height: 200),
          //     SizedBox(width: 10),
          //   MyButton01(
          //       text: '返回',
          //       containerColor: Colors.black,
          //       textColor: Colors.white,
          //       size: Size(200, 50),
          //       fontSize: 16.0,
          //       fontWeight: FontWeight.bold,
          //       onClick: (text) {
          //         SystemNavigator.pop();
          //         // Navigator.of(context).pop();
          //       },
          //     ),
          //     SizedBox(width: 4),
          //     MyButton01(
          //       text: 'Login1',
          //       containerColor: Colors.black,
          //       textColor: Colors.white,
          //       size: Size(200, 50),
          //       fontSize: 16.0,
          //       fontWeight: FontWeight.bold,
          //       onClick: (text) {
          //         var a = login();
          //         a.then((value) {
          //           print("then: ${value}");  // 输出 login() 的返回值
          //         });
          //       },
          //     ),
          //     SizedBox(width: 4),
          //     MyButton01(
          //       text: '网络请求get',
          //       containerColor: Colors.black,
          //       textColor: Colors.white,
          //       size: Size(200, 50),
          //       fontSize: 16.0,
          //       fontWeight: FontWeight.bold,
          //       onClick: (text) {
          //         print('Button pressed: $text');
          //       },
          //     ),
          //     SizedBox(width: 4),
          //     RobotButton(onClick: (text){
          //
          //     },),
          //   ],
          // )
        ],
      ),
    );
  }
}

Future<Commodity> getProductById(String id) async {
  var url = Uri.https(host, 'product/commodity/getById');
  var response = await http.post(url, body: {'access_token': Robot.accessToken,'id':id});
  print("getProductById:"+response.body);
  var a = ApiResponse<Commodity>.fromJson(jsonDecode(response.body),  (data) => Commodity.fromJson(data));
  print("getProductById: "+a.data.toString());
  print("getProductById: "+a.data!.name!);
  return a.data!;
}



Future<Commodity> getDesignPackages(String id) async {
  var url = Uri.https(host, 'designPackage/list');
  var response = await http.post(url, body: {'access_token': Robot.accessToken,'id':id});
  print("getProductById:"+response.body);
  var a = ApiResponse<Commodity>.fromJson(jsonDecode(response.body),  (data) => Commodity.fromJson(data));
  print("getProductById: "+a.data.toString());
  print("getProductById: "+a.data!.name!);
  return a.data!;
}











// Future<int> login() async {
//   print("login start");
//   var url = Uri.https(host, 'robot/login');
//   var response = await http.post(url, body: {'sn': Robot.sn});
//   var a = ApiResponse<LoginBean>.fromJson(jsonDecode(response.body),
//           (data) => LoginBean.fromJson(data)); // 传递一个从 JSON 解析 LoginBean 的方法);
//
//   print(a.data.toString());
//   if (a.data?.userId == null) {
//     print('请扫码');
//     return 0;
//   }
// Robot.userId = a.data!.userId!;
// Robot.companyId = a.data!.companyId!;
// Robot.accessToken = a.data!.accessToken!;
// print("Robot.accessToken:"+Robot.accessToken);
//   print("login end");
//   return 1;
// }

const String host = 'applet.xmlights.com';


